﻿using System;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace Uti.AMG.UserForms.Web.Infrastructure
{
    /// <summary>
    /// Filter used to detect session timeout
    /// </summary>
    internal sealed class SessionExpireFilterAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {

            HttpContext ctx = HttpContext.Current;

            // check if session is supported
            if (ctx.Session != null)
            {
                // check if a new session id was generated
                if (ctx.Session.IsNewSession)
                {
                    // If new session, but an existing cookie exists, then it must have timed out
                    string sessionCookie = ctx.Request.Headers["Cookie"];
                    if ((sessionCookie != null) && (sessionCookie.IndexOf("ASP.NET_SessionId") >= 0))
                    {
                        var message = new StringBuilder("Our apologies.  For security reasons, your session has timed out due to prolonged inactivity.  Click 'Search Courses' on the menu to start over.");
                        throw new Exception(message.ToString());
                    }
                }
            }

            base.OnActionExecuting(filterContext);
        }
    }

    /// <summary>
    /// An attribute to apply to json methods so that they don't get cached by the browser.  IE is especially egregious with caching
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
    internal sealed class CacheControlAttribute : ActionFilterAttribute
    {
        public CacheControlAttribute(HttpCacheability cacheability)
        {
            _cacheability = cacheability;
        }

        public HttpCacheability Cacheability { get { return _cacheability; } }

        private HttpCacheability _cacheability;

        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            HttpCachePolicyBase cache = filterContext.HttpContext.Response.Cache;
            cache.SetCacheability(_cacheability);
        }
    }
}